package com.sdkx.app.fragment;

import android.app.AlertDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.sdkx.app.R;
import com.sdkx.app.ViewModel.CurAirWay;
import com.sdkx.app.ViewModel.WayPointManager;
import com.sdkx.app.activitys.MainActivity;
import com.sdkx.app.datalayers.LayersFactory;
import com.sdkx.app.datalayers.FlyDirectPanel;
import com.sdkx.app.model.WayPoint;
import com.sdkx.app.dialog.AddWpWindow;
import com.sdkx.app.fragment.waypoints.TabWpFragment;
import com.sdkx.app.util.Util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cn.creable.gridgis.controls.MapControl;
import cn.creable.gridgis.geometry.Point;

public class WaypointFragment extends BaseFragment implements View.OnClickListener {
    ArrayList<Fragment> fragments = new ArrayList<>();
    private TabLayout tabLayout;
    private ViewPager viewPager;
    //   private ArrayList<String> mTitleList = new ArrayList<String>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_menu_wp1, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tabLayout = view.findViewById(R.id.tablayout);
        viewPager = view.findViewById(R.id.viewpager);
        viewPager.setOffscreenPageLimit(2);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
//        tabLayout.addTab(tabLayout.newTab().setText(R.string.nearest));
//        mTitleList.add("航点");
//        mTitleList.add("机场");
//        mTitleList.add("自定义");


        View wpview = getLayoutInflater().inflate(R.layout.wp_tab_item, null);
        TextView txtwpview = wpview.findViewById(R.id.titlename);
        txtwpview.setText("航点");
        TabLayout.Tab wptab = tabLayout.newTab();
        wptab.setCustomView(wpview);
        tabLayout.addTab(wptab);


        View airview = getLayoutInflater().inflate(R.layout.wp_tab_item, null);
        TextView txtairview = airview.findViewById(R.id.titlename);
        txtairview.setText("机场");
        TabLayout.Tab airtab = tabLayout.newTab();
        airtab.setCustomView(txtairview);
        tabLayout.addTab(airtab);

        TabLayout.Tab persiontab = tabLayout.newTab();
        View tabview = getLayoutInflater().inflate(R.layout.wp_tab_item, null);
        TextView txtpview = tabview.findViewById(R.id.titlename);

        persiontab.setCustomView(tabview);
        tabLayout.addTab(persiontab);


        fragments.add(new WpFragment());
        fragments.add(new AirFragment());
        fragments.add(new PersionFragment());
        viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) {

//            @Nullable
//            @Override
//            public CharSequence getPageTitle(int position) {
//                return mTitleList.get(position);
//            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Override
            public android.support.v4.app.Fragment getItem(int position) {
                return fragments.get(position);
            }
        });
        //  tabLayout.setupWithViewPager(viewPager);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.getTabAt(position).select();
            }

            @Override
            public void onPageScrollStateChanged(int state) {
//                tabLayout.setSelected();
            }
        });
        view.findViewById(R.id.tv_btn_return).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_btn_return://返回上一级点击事件
                //TODO implement
                //((MainActivity) getActivity()).ShowMainMenu(0);
                goBack();
                break;

//            case R.id.button:
//                //TODO implement
//                break;
//            case R.id.button2:
//                //TODO implement
//                break;
//            case R.id.button3:
//                //TODO implement
//                break;
        }
    }

    @Override
    public void onDestroyView() {
//        wplivedata.removeObservers(this);
        super.onDestroyView();
    }

    public static class AirFragment extends TabWpFragment implements View.OnClickListener {
        WayPoint wayPoint;
        PopupWindow popupWindow;
        int[] types = {WayPoint.WayPointType.MILITARY_AIRPORT.ordinal(),
                WayPoint.WayPointType.AIS_AIRPORT.ordinal(),
                WayPoint.WayPointType.AM_AIRPORT.ordinal(),
                WayPoint.WayPointType.PERSON_AIRPORT.ordinal()
        };

        @Override
        public List<WayPoint> getmWPList() {
            return WayPointManager.getItemsByTypelimit(types, 0, 20);
        }

        @Override
        protected List<WayPoint> getPageList(int curcout, int pagesize) {
            return WayPointManager.getItemsByTypelimit(types, curcout, pagesize);
        }

        @Override
        protected List<WayPoint> getSearchData(String keywords) {
            return WayPointManager.serchWayPoint(types, keywords);
        }

        @Override
        protected void onListItemClicked(View view, WayPoint point, int pos) {
            wayPoint = point;
            View menuview = getLayoutInflater().inflate(R.layout.airwaypoint_item_menu, null);
            popupWindow = new PopupWindow(menuview, 200, LinearLayout.LayoutParams.WRAP_CONTENT);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            popupWindow.setOutsideTouchable(true);
            popupWindow.setFocusable(true);
            popupWindow.showAsDropDown(view, view.getWidth() - 20, -view.getHeight(), Gravity.LEFT | Gravity.TOP);
            menuview.findViewById(R.id.airto).setOnClickListener(this);
            menuview.findViewById(R.id.delete).setVisibility(View.GONE);
            TextView  detail = menuview.findViewById(R.id.edit);
            detail.setText("详情");
            detail.setOnClickListener(this);
            menuview.findViewById(R.id.add2Route).setVisibility(View.GONE);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.airto:

                    //Point[] points = new Point[2];
                 //   points[0] = new Point(116.397535,39.906469);
//                    points[1] = ;
                    MapControl control = ((MainActivity)getActivity()).getMapControl();
                    FlyDirectPanel panel = (FlyDirectPanel)LayersFactory.getInstance().getItemByClass(FlyDirectPanel.class);
                    panel.setEndPoint(new Point( 116.302169,40.053850));
                    panel.setPointName(wayPoint.getName());
                    control.addCustomDraw(panel);
                    control.getExtent().centerAt(new Point(116.156985, 40.065789));
                    control.refresh();
                    break;
                case R.id.edit:
                    StringBuilder builder = new StringBuilder();
                    View contentview =  getLayoutInflater().inflate(R.layout.waypoint_details,null);
                   TextView content = contentview.findViewById(R.id.contentid);
                   TextView title  =  contentview.findViewById(R.id.titleid);
                   title.setText("机场航点");
                   builder.append("航点名称:  ");
                   builder.append(wayPoint.getName());
                    builder.append("\n机场类型:  ");
                    builder.append(getTypeDescribe(wayPoint));
                    builder.append("\n纬度:  ");
                    builder.append(Util.degreePatten(getContext(),wayPoint.getLatitude()));
                    builder.append("\n经度:  ");
                    builder.append(Util.degreePatten(getContext(),wayPoint.getLongitude()));
                    builder.append("\n高程:  ");
                    builder.append(wayPoint.getElevation());
                    builder.append("米");
                    content.setText(builder.toString());
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext(),AlertDialog.THEME_TRADITIONAL).create();
                    alertDialog.getWindow().addFlags(Window.FEATURE_NO_TITLE);
                    alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    alertDialog.show();
                    alertDialog.setContentView(contentview);
                    break;
            }
            if (popupWindow != null)
                popupWindow.dismiss();
        }
        public String getTypeDescribe(WayPoint point){
            String info = "";

            /**
             *         AIS_AIRPORT ,//1民用机场
             *         MILITARY_AIRPORT,//2军用机场
             *         AM_AIRPORT,//3军民合用机场
             *                 PERSON_AIRPORT,//8个人机场
             */
            WayPoint.WayPointType typeinfo = WayPoint.WayPointType.AIS_AIRPORT;

            if(WayPoint.WayPointType.AIS_AIRPORT.ordinal() == point.getType()){
                info = "民用机场";
            }else if(point.getType() == WayPoint.WayPointType.MILITARY_AIRPORT.ordinal()){
                info = "军用机场";
            }else if(point.getType() == WayPoint.WayPointType.AM_AIRPORT.ordinal()){
                info = "军民合用机场";
            }else if(point.getType() == WayPoint.WayPointType.PERSON_AIRPORT.ordinal()){
                info = "个人机场";
            }
            return info;
        }
    }

    public static class WpFragment extends TabWpFragment implements View.OnClickListener {
        WayPoint wayPoint;
        PopupWindow popupWindow;

        int[] types = {
                WayPoint.WayPointType.AIS_NDB.ordinal(),
                WayPoint.WayPointType.AIS_VOR_DME.ordinal(),
                WayPoint.WayPointType.AIS_POINT.ordinal(),
                WayPoint.WayPointType.MILITARY_POINT.ordinal()
        };

        @Override
        public List<WayPoint> getmWPList() {
            return WayPointManager.getItemsByTypelimit(types, 0, 20);
        }

        @Override
        protected List<WayPoint> getSearchData(String keywords) {
            return WayPointManager.serchWayPoint(types, keywords);
        }

        @Override
        protected List<WayPoint> getPageList(int curcout, int pagesize) {
            return WayPointManager.getItemsByTypelimit(types, curcout, pagesize);
        }

        @Override
        protected void onListItemClicked(View view, WayPoint point, int pos) {
            wayPoint = point;
            View menuview = getLayoutInflater().inflate(R.layout.airwaypoint_item_menu, null);
            popupWindow = new PopupWindow(menuview, 200, LinearLayout.LayoutParams.WRAP_CONTENT);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            popupWindow.setOutsideTouchable(true);
            popupWindow.setFocusable(true);
            popupWindow.showAsDropDown(view, view.getWidth() - 20, -view.getHeight(), Gravity.LEFT | Gravity.TOP);
            menuview.findViewById(R.id.airto).setOnClickListener(this);
//            menuview.findViewById(R.id.delete).setVisibility(View.GONE);
            menuview.findViewById(R.id.edit).setOnClickListener(this);
            menuview.findViewById(R.id.add2Route).setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.airto:
//                    wayPoint

                    break;

                case R.id.add2Route:
                    CurAirWay.getInstance().getList().add(wayPoint);
                    break;
                case R.id.edit:
                    StringBuilder builder = new StringBuilder();
                    View contentview =  getLayoutInflater().inflate(R.layout.waypoint_details,null);
                    TextView content = contentview.findViewById(R.id.contentid);
                    builder.append("航点名称:  ");
                    builder.append(wayPoint.getName());
                    builder.append("\n机场类型:  ");
                    builder.append(getTypeDescribe(wayPoint));
                    builder.append("\n纬度:  ");
                    builder.append(Util.degreePatten(getContext(),wayPoint.getLatitude()));
                    builder.append("\n经度:  ");
                    builder.append(Util.degreePatten(getContext(),wayPoint.getLongitude()));
                    builder.append("\n高程:  ");
                    builder.append(wayPoint.getElevation());
                    builder.append("米");
                    content.setText(builder.toString());
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext(),AlertDialog.THEME_TRADITIONAL).create();
                    alertDialog.getWindow().addFlags(Window.FEATURE_NO_TITLE);
                    alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    alertDialog.show();
                    alertDialog.setContentView(contentview);
                    break;
            }
            if (popupWindow != null)
                popupWindow.dismiss();
        }
        public String getTypeDescribe(WayPoint point){
            String info = "";

            /**
             *   AIS_NDB,//4民用航点NDB
             *         AIS_VOR_DME,//5民用航点VOR,DME
             *         AIS_POINT,//6民用航点
             *         MILITARY_POINT,//7军用航点
             */
            if(WayPoint.WayPointType.AIS_NDB.ordinal() == point.getType()){
                info = "民用航点NDB";
            }else if(point.getType() == WayPoint.WayPointType.AIS_VOR_DME.ordinal()){
                info = "民用航点VOR,DME";
            }else if(point.getType() == WayPoint.WayPointType.AIS_POINT.ordinal()){
                info = "民用航点";
            }else if(point.getType() == WayPoint.WayPointType.MILITARY_POINT.ordinal()){
                info = "军用航点";
            }
            return info;
        }
    }

    public static class PersionFragment extends TabWpFragment implements View.OnClickListener {
        WayPoint wayPoint;
        PopupWindow popupWindow;
        int curPos;
        int[] types = {
                WayPoint.WayPointType.PERSON_POINT.ordinal()
        };

        //        Observer<WayPoint> observer = new Observer<WayPoint>() {
//            @Override
//            public void onChanged(@Nullable WayPoint point) {
//                mWPList.add(point);
//                Collections.sort(mWPList, new Comparator<WayPoint>() {
//                    @Override
//                    public int compare(WayPoint o1, WayPoint o2) {
//                        return o1.getName().compareTo(o2.getName());
//                    }
//                });
//                wpListAdapter.notifyDataSetChanged();
//            }
//        };
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
            View addview = view.findViewById(R.id.btn_add);
            addview.setVisibility(View.VISIBLE);
            addview.setOnClickListener(this);
        }

        @Override
        public List<WayPoint> getmWPList() {
            return WayPointManager.getItemsByTypelimit(types, 0, 20);
        }

        @Override
        protected List<WayPoint> getSearchData(String keywords) {
            return WayPointManager.serchWayPoint(types, keywords);
        }

        @Override
        protected List<WayPoint> getPageList(int curcout, int pagesize) {
            return WayPointManager.getItemsByTypelimit(types, curcout, pagesize);
        }

        @Override
        public void onDestroyView() {
//            AirDataViewModel mNameViewModel = ViewModelProviders.of(getActivity()).get(AirDataViewModel.class);
//            mNameViewModel.getWayPointLiveData().removeObserver(observer); //observe(getActivity(),observer);
            super.onDestroyView();
        }

        @Override
        protected void onListItemClicked(View view, WayPoint point, int pos) {
            curPos = pos;
            wayPoint = point;
            View menuview = getLayoutInflater().inflate(R.layout.airwaypoint_item_menu, null);
            popupWindow = new PopupWindow(menuview, 200, LinearLayout.LayoutParams.WRAP_CONTENT);
            popupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            popupWindow.setOutsideTouchable(true);
            popupWindow.setFocusable(true);
            popupWindow.showAsDropDown(view, view.getWidth() - 20, -view.getHeight(), Gravity.LEFT | Gravity.TOP);
            menuview.findViewById(R.id.airto).setOnClickListener(this);
            menuview.findViewById(R.id.delete).setOnClickListener(this);
            menuview.findViewById(R.id.edit).setOnClickListener(this);
            menuview.findViewById(R.id.add2Route).setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_add: {
                    AddWpWindow mModiWPDialog = new AddWpWindow(getActivity());
                    mModiWPDialog.setCallback(new AddWpWindow.IWayPointCallback() {

                        @Override
                        public void onAdd(WayPoint point) {
                            mWPList.add(point);
                            Collections.sort(mWPList, new Comparator<WayPoint>() {
                                @Override
                                public int compare(WayPoint o1, WayPoint o2) {
                                    return o1.getName().compareTo(o2.getName());
                                }
                            });
                            getWpListAdapter().notifyDataSetChanged();
                        }

                        @Override
                        public void onUpdate(WayPoint point) {

                        }
                    });
                    mModiWPDialog.show();
                }
                break;
                case R.id.airto:
                    MapControl control = ((MainActivity)getActivity()).getMapControl();
                    FlyDirectPanel panel = (FlyDirectPanel)LayersFactory.getInstance().getItemByClass(FlyDirectPanel.class);
                    panel.setEndPoint(new Point( 116.302169,40.053850));
                    panel.setPointName(wayPoint.getName());
                    control.addCustomDraw(panel);
                    control.getExtent().centerAt(new Point(116.156985, 40.065789));
                    control.refresh();
                    break;
                case R.id.delete:
                    WayPointManager.delete(wayPoint.getName());
                    wpListAdapter.deleteitem(curPos);

                    break;
                case R.id.edit: {
                    AddWpWindow mModiWPDialog = new AddWpWindow(getActivity(), wayPoint);
                    mModiWPDialog.setCallback(new AddWpWindow.IWayPointCallback() {

                        @Override
                        public void onAdd(WayPoint point) {
                            mWPList.add(point);
                            Collections.sort(mWPList, new Comparator<WayPoint>() {
                                @Override
                                public int compare(WayPoint o1, WayPoint o2) {
                                    return o1.getName().compareTo(o2.getName());
                                }
                            });
                            wpListAdapter.notifyDataSetChanged();
                        }

                        @Override
                        public void onUpdate(WayPoint point) {
                            for (WayPoint po : mWPList) {
                                if (po.getId() == point.getId()) {
                                    mWPList.remove(po);
                                    break;
                                }
                            }
                            mWPList.add(point);
                            Collections.sort(mWPList, new Comparator<WayPoint>() {
                                @Override
                                public int compare(WayPoint o1, WayPoint o2) {
                                    return o1.getName().compareTo(o2.getName());
                                }
                            });
                            wpListAdapter.notifyDataSetChanged();
                        }
                    });

                    mModiWPDialog.show();
                }
                return;
                case R.id.add2Route:
                    CurAirWay.getInstance().getList().add(wayPoint);
                    break;
            }
            if (popupWindow != null)
                popupWindow.dismiss();
        }
    }
}